Array.prototype.treeToList = function (children = "children", pid, id) {
  const list = [];
  const queue = [...this];
  if (pid) {
    if (!id) {
      id = "id";
    }
    for (const node of queue) {
      node[pid] = 0;
    }
  }

  while (queue.length) {
    const node = queue.shift();

    node[pid];
    const childrenData = node[children];

    if (childrenData) {
      if (pid) {
        for (const no of childrenData) {
          no[pid] = node[id];
        }
      }
      queue.push(...childrenData);
    }
    list.push(node);
  }
  return list;
};

Array.prototype.listToTree = function (
  pid = "pid",
  id = "id",
  children = "children"
) {
  const tree = [];
  for (const node of this) {
    // pid 空 或 0 为根节点
    if (!node[pid] || node[pid] === 0) {
      let p = { ...node };
      p[children] = getChildren(p[id], this);
      tree.push(p);
    }
  }
  function getChildren(id, list) {
    const children = [];
    for (const node of list) {
      if (node[pid] === id) {
        children.push(node);
      }
    }

    for (const node of children) {
      const children = getChildren(node[id], list);
      if (children.length) {
        node[children] = children;
      }
    }
    return children;
  }

  return tree;
};
